package cn.eclass.utils;

import cn.eclass.entity.CategoryEntity;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import sun.misc.BASE64Encoder;

/**
 *
 * @author Guan Junming <junming.guan at kisters.cn>
 */
public class Helper {

    private static final String CONFIG_FOLDER = "conf";
    private static final String DEFAULT_CONFIG = "eketang.properties";
    private static final Logger logger = Helper.getLogger();

    public static String parseName(String name, String theRequire) {
        if (!"".equals(theRequire)) {
            return " and " + name + preFilter(theRequire);
        }
        return theRequire;
    }
    //

    public static String preFilter(String theRequire) {
        if (theRequire.contains("*")) {
            return " like '" + theRequire.replace("*", "%") + "'";
        } else if (theRequire.contains(",")) {
            String[] theReqStrings = theRequire.split(",");
            String inSql = " in (";
            for (String one : theReqStrings) {
                inSql += "'" + one + "',";
            }
            inSql = inSql.substring(0, inSql.length() - 1);
            inSql += ")";
            return inSql;
        } else {
            return " = '" + theRequire + "'";
        }
    }

    public static Gson getJsonParser(Boolean withNull) {
        if (withNull) {
            return new GsonBuilder().serializeNulls().create();
        } else {
            return getJsonParse();
        }
    }

    public static String intList2Str(List<Integer> list) {
        StringBuffer sb = new StringBuffer();
        sb.append(list.get(0));
        for (int index = 1; index < list.size(); index++) {
            sb.append("," + list.get(index));
        }
        return sb.toString();
    }

    public static Gson getJsonParse() {
        return new Gson();
    }

    public static String ucfirst(String string) {
        String upper = string.toUpperCase();
        StringBuilder newString = new StringBuilder(upper.substring(0, 1));
        newString.append(string.substring(1));
        return newString.toString();
    }

    /**
     * get a propertie file under WEB-INF/conf
     *
     * @param configName
     * @return
     */
    public static Properties getConfig(String configName) {
        Properties pro = new Properties();

        String configPath = new File(Helper.class.getResource("/").getPath()).getParent();
        StringBuilder stringBuilder = new StringBuilder(configPath);
        String thePath = stringBuilder.append(File.separator).append(CONFIG_FOLDER).append(File.separator).append(configName).toString();

        try {
            pro.load(new FileInputStream(new File(thePath)));
            pro.setProperty("configPath", configPath + File.separator + "conf");
        } catch (IOException ex) {
            logger.error(ex);
        }
        return pro;
    }

    public static Properties getConfig() {
        return getConfig(DEFAULT_CONFIG);
    }

    public static String toUTF8(String theString) {
        byte[] b;
        String s = null;
        try {
            b = theString.getBytes("ISO-8859-1");
            s = new String(b, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            logger.error(ex);
        }
        return s;
    }

    public static String Md5(String str) {
        if (null == str) {
            return "";
        }
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            BASE64Encoder base64en = new BASE64Encoder();
            String newstr = base64en.encode(md5.digest(str.getBytes("utf-8")));
            return newstr.trim();
        } catch (Exception e) {
            return str.trim();
        }
    }

    /**
     * get a UUID String
     *
     * @return String UUID
     */
    public static String getUuid() {
        String s = UUID.randomUUID().toString();
        //remove "-"
        return s.substring(0, 8) + s.substring(9, 13) + s.substring(14, 18) + s.substring(19, 23) + s.substring(24);
    }

    public static String getUploadFilename(Part part) {
        String contentDisposition = part.getHeader("content-disposition");
        return contentDisposition.substring(contentDisposition.lastIndexOf("filename=") + 10, contentDisposition.length() - 1);
    }

    public static String getUploadFilePath(HttpServletRequest request, Properties config, String module, String partName) {
        String fileName = "";
        String fileUrl = "";
        String uploadPath = config.getProperty("uploadPath") + File.separator + module;

        try {
            Part part = request.getPart(partName);
            fileName = getUploadFilename(part);
            File file = new File(uploadPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            uploadPath = uploadPath + File.separator + fileName;
            part.write(uploadPath);
            fileUrl = config.getProperty("uploadUrl") + "/" + module + "/" + fileName;

            //docBase + upload +  module + filename;
        } catch (IllegalStateException ex) {
            logger.error(ex);
        } catch (ServletException ex) {
            logger.error(ex);
        } catch (IOException ex) {
            fileName = "";
            logger.error(ex);
        }
        return fileUrl;
    }

    public static String pageCatUrl(String url, int catId, int pageId) {
        String extendUrl = url;
        if (!url.contains("?")) {
            url += "?";
        }

        if (url.contains("pageId")) {
            url.replaceFirst("pageId=\\d+&*", "");
        }
        url = url + "pageId=" + pageId;

        if (url.contains("catId")) {
            url.replaceFirst("catId=\\d+&*", "");
        }
        url = url + "catId=" + catId;

        return extendUrl;

    }

    public static String getInitPageUrl(String url, int catId) {
        return pageCatUrl(url, catId, 1);
    }

    public static String getCatName(int catId) {
        if (catId == 0) {
            return "分类目录";
        }
        CategoryEntity cat = BeanFactory.factory.getCatBean().getByIdInTree(catId);
        return cat.getName();
    }

    public static String getSingleBc(String url, int catId) {
        String res = "<a href=";
        res += getInitPageUrl(url, catId);
        res += ">" + getCatName(catId);
        res += "</a>";
        return res;
    }

    public static String getWholeBc(String url, int catId) {
        if (catId == 0) {
            return getSingleBc(url, catId);
        }

        CategoryEntity cat = BeanFactory.factory.getCatBean().getByIdInTree(catId);
        if (cat.getParent().getId() == 0) {
            String bc = getSingleBc(url, 0);
            bc += ">" + getSingleBc(url, catId);
            return bc;
        }
        CategoryEntity parent = cat.getParent();
        String bc = getSingleBc(url, 0) + ">" + getSingleBc(url, parent.getId()) + ">" + getSingleBc(url, cat.getId());
        return bc;
    }
//    public void getWholeBc(String url, int catId, StringBuffer bc) {
//    	if(catId == 0) {
//    		bc.insert(0,getSingleBc(url, catId));
//    		return;
//    	}
//    	
//    	
//    	CategoryEntity cat = BeanFactory.factory.getCatBean().getByIdInTree(catId);
//    	if(cat.getParent() == )
//    }

    public static List<HashMap<String, String>> buildField(Field[] fields, String module) {
        List<HashMap<String, String>> theFields = new ArrayList<HashMap<String, String>>();
        Properties adminUi = Helper.getConfig("admin-ui.properties");
        for (Field field : fields) {
            HashMap<String, String> oneField = new HashMap<String, String>();
            String fieldName = field.getName();
            oneField.put("name", fieldName);
            oneField.put("label", adminUi.getProperty(module + "." + fieldName, fieldName));
            theFields.add(oneField);
        }
        return theFields;
    }

    public static String getDefault(String value, String defaultValue) {
        if (null == value) {
            return defaultValue;
        }
        return value;
    }

    public static Logger getLogger() {
        Logger logger = Logger.getRootLogger();
        PropertyConfigurator.configure(Helper.getConfig("log4j.properties"));
        return logger;
    }
}
